package com.xiaoyu.shenyou.shenyouv1.controller;

import com.xiaoyu.shenyou.shenyouv1.common.result.Result;
import com.xiaoyu.shenyou.shenyouv1.dto.UserDTO;
import com.xiaoyu.shenyou.shenyouv1.properties.JwtProperties;
import com.xiaoyu.shenyou.shenyouv1.services.UserService;
import com.xiaoyu.shenyou.shenyouv1.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        //卡帕id
        int userId = userDTO.getUser_id();
        //判断缓存当中是否存在该id
        boolean cache = userService.survivalCache(userId);
        if (cache) {
            //存在返回
            Result<String> error = Result.error("ID正在使用！");
            return error;
        }
        //数据库查询
        boolean hasUser = userService.queryUser(userId);
        if (hasUser) {
            //生成token
            String userIdStr = String.valueOf(userId);
            String token = JwtUtil.createToken(userIdStr, jwtProperties.getSecretKey(), jwtProperties.getLongTime());
            Result<String> success = Result.success(token);
            //存入redis中
            redisTemplate.opsForValue().set(userIdStr, userIdStr);
            //设置5秒过期
            redisTemplate.expire(userIdStr, 5, TimeUnit.SECONDS);
            return success;
        }
        Result<String> error = Result.error("ID未授权");
        return error;
    }
}
